﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace zhangmenren.Db
{
        public class BaseRepository
        {
            private readonly string connectionString;

            public BaseRepository()
            {
                connectionString = @"Server=39.98.43.168;database=zhangmenren;uid=sa;pwd=Ab2018zhang;";
            }

            private IDbConnection CreateSqlConnection()
            {
                return new SqlConnection(connectionString);
            }

            /// <summary>
            /// 不带事物锁的执行
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="handler"></param>
            /// <returns></returns>
            protected T Execute<T>(Func<IDbConnection, T> handler)
            {
                using (IDbConnection connection = CreateSqlConnection())
                {
                    try
                    {
                        return handler(connection);
                    }
                    catch (Exception ex)
                    {
                        T t = System.Activator.CreateInstance<T>();
                    var temp=ex.Message;
                        return t;
                    }

                }
            }

            protected Task<T> ExecuteAsync<T>(Func<IDbConnection, Task<T>> handler)
            {
                using (IDbConnection connection = CreateSqlConnection())
                {
                    return handler(connection);
                }
            }

            /// <summary>
            /// 带事物锁的执行
            /// </summary>
            /// <param name="action"></param>
            protected void ExecuteTransaction(Action<IDbConnection, IDbTransaction> action)
            {
                using (IDbConnection connection = CreateSqlConnection())
                {
                    connection.Open();
                    IDbTransaction transaction = connection.BeginTransaction();
                    try
                    {
                        action(connection, transaction);
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw ex;
                    }
                }
            }

        }
}
